import axios, { AxiosError, type InternalAxiosRequestConfig, type AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
const service = axios.create({
  baseURL: import.meta.env.VUE_APP_BASE_API,
  timeout: 3000000,
  withCredentials: true // 跨域时候允许携带凭证
})

//  request interceptor 接口请求拦截
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStore()
    const token: string = userStore.token
    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

//  response interceptor 接口响应拦截
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data
    if (res.code !== 200) {
      showErrMessage(res)
      return Promise.reject(new Error(res.msg || 'Error'))
    }
    return res
  },
  (error: AxiosError) => {
    showErrMessage({ msg: '请求出错，请重试' })
    return Promise.reject(error)
  }
)

/**
 * @description 显示错误消息
 * err 错误信息
 * type 消息类型
 * duration 消息持续时间
 */
function showErrMessage(err: any, type: any = 'error', duration: number = 1500) {
  ElMessage({
    message: err.msg,
    type: type,
    duration: duration
  })
}

export default service
